package com.dc.filter;

import com.alibaba.druid.support.json.JSONUtils;
import com.dc.constant.Constants;
import com.dc.constant.MessageConstant;
import com.dc.model.AjaxResult;
import com.dc.service.JwtTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * token过滤器 验证token有效性
 * 
 * @author ruoyi
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private JwtTokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {

        String servletPath = request.getServletPath();
        String method = request.getMethod();

        if(servletPath.contains(Constants.DEFAULT_RESOURCE_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }

        if(Constants.URL_WHITE_LIST.contains(servletPath)) {   // 登录、注册 url，放过
            chain.doFilter(request, response);
            return;
        }

        boolean b = swaggerFilter(servletPath);
        if(b) {
            chain.doFilter(request, response);
            return;
        }

        if(method.equals("OPTIONS")) {
            chain.doFilter(request, response);
            return;
        }

        // token 处理开始
        String token = request.getHeader(Constants.TAG_TOKEN);
        if (ObjectUtils.isEmpty(token)) {               // header没有token，失败
            loginFail(response);
            return;
        }
        String userName = tokenService.getUserNameFromToken(token);
        if(ObjectUtils.isEmpty(userName)) {            // token解析失败，失败
            loginFail(response);
            return;
        }
        request.setAttribute("userName", userName);   // 在请求中放入 userName

        log.info(method + " : " + servletPath);

        chain.doFilter(request, response);
    }

    private void loginFail(HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONUtils.toJSONString(AjaxResult.error(MessageConstant.ILLEGAL_REQUEST)));
        response.getWriter().flush();
    }

    /**
     * 如果是 swagger 的路径，则返回true，否则返回 false
     * @param servletPath
     * @return
     */
    private boolean swaggerFilter(String servletPath) {
        if(servletPath.contains("/swagger-ui/")
                || servletPath.contains("/swagger-resources")
                || servletPath.contains("/v3/")) {
            return true;
        }
        return false;
    }
}
